package com.ruoyi.system.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.RoomRecordmessage;
import com.ruoyi.system.service.IRoomRecordmessageService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.service.ISysUserService;

/**
 * 房间信息记录Controller
 * 
 * @author xyz
 * @date 2025-07-01
 */
@RestController
@RequestMapping("/system/roomrecord")
public class RoomRecordmessageController extends BaseController
{
    @Autowired
    private IRoomRecordmessageService roomRecordmessageService;
    @Autowired
    private ISysUserService userService;

    /**
     * 查询房间信息记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:roomrecord:list')")
    @GetMapping("/list")
    public TableDataInfo list(RoomRecordmessage roomRecordmessage)
    {
        startPage();
        List<RoomRecordmessage> list = roomRecordmessageService.selectRoomRecordmessageList(roomRecordmessage);
        return getDataTable(list);
    }

    /**
     * 导出房间信息记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:roomrecord:export')")
    @Log(title = "房间信息记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RoomRecordmessage roomRecordmessage)
    {
        List<RoomRecordmessage> list = roomRecordmessageService.selectRoomRecordmessageList(roomRecordmessage);
        ExcelUtil<RoomRecordmessage> util = new ExcelUtil<RoomRecordmessage>(RoomRecordmessage.class);
        util.exportExcel(response, list, "房间信息记录数据");
    }

    /**
     * 获取房间信息记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:roomrecord:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(roomRecordmessageService.selectRoomRecordmessageById(id));
    }

    /**
     * 新增房间信息记录
     */
    @PreAuthorize("@ss.hasPermi('system:roomrecord:add')")
    @Log(title = "房间信息记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RoomRecordmessage roomRecordmessage)
    {
        return toAjax(roomRecordmessageService.insertRoomRecordmessage(roomRecordmessage));
    }

    /**
     * 修改房间信息记录
     */
    @PreAuthorize("@ss.hasPermi('system:roomrecord:edit')")
    @Log(title = "房间信息记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RoomRecordmessage roomRecordmessage)
    {
        return toAjax(roomRecordmessageService.updateRoomRecordmessage(roomRecordmessage));
    }

    /**
     * 删除房间信息记录
     */
    @PreAuthorize("@ss.hasPermi('system:roomrecord:remove')")
    @Log(title = "房间信息记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(roomRecordmessageService.deleteRoomRecordmessageByIds(ids));
    }

    /**
     * 根据业务员userId查询所在房间信息记录
     */
    @GetMapping("/searchYeWuYuanRoomRecord")
    public AjaxResult searchYeWuYuanRoomRecord(@RequestParam("userId") String userId) {
        if (org.apache.commons.lang3.StringUtils.isBlank(userId)) {
            return error("业务员ID不能为空");
        }
        org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(RoomRecordmessageController.class);
        log.info("查询业务员所在房间记录，业务员ID: {}", userId);
        // 查询所有房间记录
        List<RoomRecordmessage> allRecords = roomRecordmessageService.selectRoomRecordmessageList(new RoomRecordmessage());
        List<RoomRecordmessage> resultRecords = new java.util.ArrayList<>();
        for (RoomRecordmessage record : allRecords) {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(record.getGroupName())) {
                String[] userIds = record.getGroupName().split(",");
                for (String roomUserId : userIds) {
                    if (roomUserId.equals(userId)) {
                        resultRecords.add(record);
                        log.info("找到业务员所在房间记录，记录ID: {}, 房间ID: {}", record.getId(), record.getRoomId());
                        break;
                    }
                }
            }
        }
        log.info("业务员所在房间记录数量: {}", resultRecords.size());
        return success(resultRecords);
    }

    /**
     * 根据房间名称和日期搜索房间记录信息（管理层专用）
     */
    @GetMapping("/searchRoomRecordByCondition")
    public AjaxResult searchRoomRecordByCondition(@RequestParam(value = "cc", required = false) String cc, 
                                                 @RequestParam(value = "recordTime", required = false) String recordTime) {
        org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(RoomRecordmessageController.class);
        log.info("搜索房间记录，房间名称: {}, 日期: {}", cc, recordTime);
        
        // 构建查询条件
        RoomRecordmessage queryCondition = new RoomRecordmessage();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(cc)) {
            queryCondition.setCc(cc);
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(recordTime)) {
            try {
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
                java.util.Date date = sdf.parse(recordTime);
                queryCondition.setRecordTime(date);
            } catch (Exception e) {
                log.warn("日期格式解析失败: {}", recordTime);
            }
        }
        
        List<RoomRecordmessage> resultRecords = roomRecordmessageService.selectRoomRecordmessageList(queryCondition);
        log.info("查询到房间记录数: {}", resultRecords.size());
        
        // 如果使用日期搜索但没有结果，尝试使用日期范围查询
        if (org.apache.commons.lang3.StringUtils.isNotBlank(recordTime) && resultRecords.isEmpty()) {
            log.info("精确日期查询无结果，尝试日期范围查询");
            try {
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
                java.util.Date searchDate = sdf.parse(recordTime);
                
                // 获取当天的开始和结束时间
                java.util.Calendar cal = java.util.Calendar.getInstance();
                cal.setTime(searchDate);
                cal.set(java.util.Calendar.HOUR_OF_DAY, 0);
                cal.set(java.util.Calendar.MINUTE, 0);
                cal.set(java.util.Calendar.SECOND, 0);
                cal.set(java.util.Calendar.MILLISECOND, 0);
                java.util.Date startOfDay = cal.getTime();
                
                cal.set(java.util.Calendar.HOUR_OF_DAY, 23);
                cal.set(java.util.Calendar.MINUTE, 59);
                cal.set(java.util.Calendar.SECOND, 59);
                cal.set(java.util.Calendar.MILLISECOND, 999);
                java.util.Date endOfDay = cal.getTime();
                
                // 使用自定义查询方法进行日期范围查询
                resultRecords = roomRecordmessageService.selectRoomRecordmessageByDateRange(cc, startOfDay, endOfDay);
                log.info("日期范围查询结果数: {}", resultRecords.size());
            } catch (Exception e) {
                log.error("日期范围查询失败: {}", e.getMessage());
            }
        }
        
        return success(resultRecords);
    }

    /**
     * 根据房间名称和时间查询房间记录信息（简化版）
     */
    @GetMapping("/searchRoomRecordByCcAndTime")
    public AjaxResult searchRoomRecordByCcAndTime(@RequestParam(value = "cc", required = false) String cc, 
                                                 @RequestParam(value = "recordTime", required = false) String recordTime) {
        org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(RoomRecordmessageController.class);
        log.info("简化搜索房间记录，房间名称: {}, 日期: {}", cc, recordTime);
        
        List<RoomRecordmessage> resultRecords = roomRecordmessageService.selectRoomRecordmessageByCcAndTime(cc, recordTime);
        log.info("简化查询到房间记录数: {}", resultRecords.size());
        
        // 构建包含用户详细信息的响应数据
        java.util.List<java.util.Map<String, Object>> result = new java.util.ArrayList<>();
        
        // 收集所有涉及的用户ID
        java.util.Set<Long> allUserIds = new java.util.HashSet<>();
        for (RoomRecordmessage record : resultRecords) {
            // 收集groupName中的用户ID
            if (org.apache.commons.lang3.StringUtils.isNotBlank(record.getGroupName())) {
                String[] userIds = record.getGroupName().split(",");
                for (String uidStr : userIds) {
                    try {
                        Long uid = Long.parseLong(uidStr.trim());
                        allUserIds.add(uid);
                    } catch (Exception e) {
                        // 跳过无效的用户ID
                    }
                }
            }
            
            // 收集其他相关用户ID
            if (record.getBookerId() != null) {
                allUserIds.add(record.getBookerId());
            }
            if (record.getServiceStaffId() != null) {
                allUserIds.add(record.getServiceStaffId());
            }
            if (record.getDjId() != null) {
                allUserIds.add(record.getDjId());
            }
        }
        
        // 批量查询所有用户信息
        java.util.Map<Long, com.ruoyi.common.core.domain.entity.SysUser> userMap = new java.util.HashMap<>();
        if (!allUserIds.isEmpty()) {
            for (Long uid : allUserIds) {
                try {
                    com.ruoyi.common.core.domain.entity.SysUser user = userService.selectUserById(uid);
                    if (user != null) {
                        userMap.put(uid, user);
                    }
                } catch (Exception e) {
                    log.warn("查询用户信息失败，用户ID: {}, 错误: {}", uid, e.getMessage());
                }
            }
        }
        
        for (RoomRecordmessage record : resultRecords) {
            java.util.Map<String, Object> enhancedRecord = new java.util.HashMap<>();
            
            // 复制原记录的所有属性，包括 createdAt
            enhancedRecord.put("id", record.getId());
            enhancedRecord.put("roomId", record.getRoomId());
            enhancedRecord.put("area", record.getArea());
            enhancedRecord.put("price", record.getPrice());
            enhancedRecord.put("status", record.getStatus());
            enhancedRecord.put("groupName", record.getGroupName());
            enhancedRecord.put("purpose", record.getPurpose());
            enhancedRecord.put("bookerId", record.getBookerId());
            enhancedRecord.put("serviceStaffId", record.getServiceStaffId());
            enhancedRecord.put("djId", record.getDjId());
            enhancedRecord.put("startTime", record.getStartTime());
            enhancedRecord.put("endTime", record.getEndTime());
            enhancedRecord.put("bookerEntryCount", record.getBookerEntryCount());
            enhancedRecord.put("serviceStaffEntryCount", record.getServiceStaffEntryCount());
            enhancedRecord.put("djEntryCount", record.getDjEntryCount());
            enhancedRecord.put("totalAmount", record.getTotalAmount());
            enhancedRecord.put("discount", record.getDiscount());
            enhancedRecord.put("serviceStaffPayment", record.getServiceStaffPayment());
            enhancedRecord.put("djPayment", record.getDjPayment());
            enhancedRecord.put("salespersonPayment", record.getSalespersonPayment());
            enhancedRecord.put("aa", record.getAa());
            enhancedRecord.put("bb", record.getBb());
            enhancedRecord.put("cc", record.getCc());
            enhancedRecord.put("remark", record.getRemark());
            enhancedRecord.put("feedback", record.getFeedback());
            enhancedRecord.put("ee", record.getEe());
            enhancedRecord.put("ff", record.getFf());
            enhancedRecord.put("recordTime", record.getRecordTime());
            enhancedRecord.put("createdAt", record.getCreatedAt()); // 添加开始时间字段
            
            // 添加业务员详细信息
            if (org.apache.commons.lang3.StringUtils.isNotBlank(record.getGroupName())) {
                java.util.List<java.util.Map<String, Object>> businessUsers = new java.util.ArrayList<>();
                String[] userIds = record.getGroupName().split(",");
                for (String uidStr : userIds) {
                    try {
                        Long uid = Long.parseLong(uidStr.trim());
                        com.ruoyi.common.core.domain.entity.SysUser u = userMap.get(uid);
                        if (u != null) {
                            java.util.Map<String, Object> userInfo = new java.util.HashMap<>();
                            userInfo.put("userId", u.getUserId());
                            userInfo.put("userName", u.getUserName());
                            userInfo.put("employeeId", u.getEmployeeId());
                            userInfo.put("level", u.getLevel());
                            businessUsers.add(userInfo);
                        }
                    } catch (Exception e) {
                        // 跳过无效的用户ID
                    }
                }
                enhancedRecord.put("businessUsers", businessUsers);
            }
            
            // 添加订房人详细信息
            if (record.getBookerId() != null) {
                com.ruoyi.common.core.domain.entity.SysUser booker = userMap.get(record.getBookerId());
                if (booker != null) {
                    enhancedRecord.put("bookerName", booker.getUserName());
                }
            }
            
            // 添加服务员详细信息
            if (record.getServiceStaffId() != null) {
                com.ruoyi.common.core.domain.entity.SysUser serviceStaff = userMap.get(record.getServiceStaffId());
                if (serviceStaff != null) {
                    enhancedRecord.put("serviceStaffName", serviceStaff.getUserName());
                }
            }
            
            // 添加DJ详细信息
            if (record.getDjId() != null) {
                com.ruoyi.common.core.domain.entity.SysUser dj = userMap.get(record.getDjId());
                if (dj != null) {
                    enhancedRecord.put("djName", dj.getUserName());
                }
            }
            
            result.add(enhancedRecord);
        }
        
        return success(result);
    }

    /**
     * 根据用户ID查询所在房间记录信息
     */
    @GetMapping("/searchRoomRecordUser")
    public AjaxResult searchRoomRecordUser(@RequestParam("userId") String userId) {
        if (org.apache.commons.lang3.StringUtils.isBlank(userId)) {
            return error("用户ID不能为空");
        }
        
        org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(RoomRecordmessageController.class);
        log.info("查询用户所在房间记录，用户ID: {}", userId);
        
        List<RoomRecordmessage> resultRecords = roomRecordmessageService.selectRoomRecordmessageByUserId(userId);
        log.info("查询到房间记录数: {}", resultRecords.size());
        
        // 收集所有涉及的用户ID
        java.util.Set<Long> allUserIds = new java.util.HashSet<>();
        for (RoomRecordmessage record : resultRecords) {
            // 收集groupName中的用户ID
            if (org.apache.commons.lang3.StringUtils.isNotBlank(record.getGroupName())) {
                String[] userIds = record.getGroupName().split(",");
                for (String uidStr : userIds) {
                    try {
                        Long uid = Long.parseLong(uidStr.trim());
                        allUserIds.add(uid);
                    } catch (Exception e) {
                        // 跳过无效的用户ID
                    }
                }
            }
            
            // 收集其他相关用户ID
            if (record.getBookerId() != null) {
                allUserIds.add(record.getBookerId());
            }
            if (record.getServiceStaffId() != null) {
                allUserIds.add(record.getServiceStaffId());
            }
            if (record.getDjId() != null) {
                allUserIds.add(record.getDjId());
            }
        }
        
        // 批量查询所有用户信息
        java.util.Map<Long, com.ruoyi.common.core.domain.entity.SysUser> userMap = new java.util.HashMap<>();
        if (!allUserIds.isEmpty()) {
            for (Long uid : allUserIds) {
                try {
                    com.ruoyi.common.core.domain.entity.SysUser user = userService.selectUserById(uid);
                    if (user != null) {
                        userMap.put(uid, user);
                    }
                } catch (Exception e) {
                    log.warn("查询用户信息失败，用户ID: {}, 错误: {}", uid, e.getMessage());
                }
            }
        }
        log.info("查询到的用户信息数量: {}", userMap.size());
        
        // 构建包含用户详细信息的响应数据
        java.util.List<java.util.Map<String, Object>> result = new java.util.ArrayList<>();
        
        for (RoomRecordmessage record : resultRecords) {
            java.util.Map<String, Object> enhancedRecord = new java.util.HashMap<>();
            
            // 复制原记录的所有属性
            enhancedRecord.put("id", record.getId());
            enhancedRecord.put("roomId", record.getRoomId());
            enhancedRecord.put("area", record.getArea());
            enhancedRecord.put("price", record.getPrice());
            enhancedRecord.put("status", record.getStatus());
            enhancedRecord.put("groupName", record.getGroupName());
            enhancedRecord.put("purpose", record.getPurpose());
            enhancedRecord.put("bookerId", record.getBookerId());
            enhancedRecord.put("serviceStaffId", record.getServiceStaffId());
            enhancedRecord.put("djId", record.getDjId());
            enhancedRecord.put("startTime", record.getStartTime());
            enhancedRecord.put("endTime", record.getEndTime());
            enhancedRecord.put("bookerEntryCount", record.getBookerEntryCount());
            enhancedRecord.put("serviceStaffEntryCount", record.getServiceStaffEntryCount());
            enhancedRecord.put("djEntryCount", record.getDjEntryCount());
            enhancedRecord.put("totalAmount", record.getTotalAmount());
            enhancedRecord.put("discount", record.getDiscount());
            enhancedRecord.put("serviceStaffPayment", record.getServiceStaffPayment());
            enhancedRecord.put("djPayment", record.getDjPayment());
            enhancedRecord.put("salespersonPayment", record.getSalespersonPayment());
            enhancedRecord.put("aa", record.getAa());
            enhancedRecord.put("bb", record.getBb());
            enhancedRecord.put("cc", record.getCc());
            enhancedRecord.put("remark", record.getRemark());
            enhancedRecord.put("feedback", record.getFeedback());
            enhancedRecord.put("ee", record.getEe());
            enhancedRecord.put("ff", record.getFf());
            enhancedRecord.put("recordTime", record.getRecordTime());
            
            // 添加业务员详细信息
            if (org.apache.commons.lang3.StringUtils.isNotBlank(record.getGroupName())) {
                java.util.List<java.util.Map<String, Object>> businessUsers = new java.util.ArrayList<>();
                String[] userIds = record.getGroupName().split(",");
                for (String uidStr : userIds) {
                    try {
                        Long uid = Long.parseLong(uidStr.trim());
                        com.ruoyi.common.core.domain.entity.SysUser u = userMap.get(uid);
                        if (u != null) {
                            java.util.Map<String, Object> userInfo = new java.util.HashMap<>();
                            userInfo.put("userId", u.getUserId());
                            userInfo.put("userName", u.getUserName());
                            userInfo.put("employeeId", u.getEmployeeId());
                            userInfo.put("level", u.getLevel());
                            businessUsers.add(userInfo);
                        }
                    } catch (Exception e) {
                        // 跳过无效的用户ID
                    }
                }
                enhancedRecord.put("businessUsers", businessUsers);
            }
            
            // 添加订房人详细信息
            if (record.getBookerId() != null) {
                com.ruoyi.common.core.domain.entity.SysUser booker = userMap.get(record.getBookerId());
                if (booker != null) {
                    enhancedRecord.put("bookerName", booker.getUserName());
                }
            }
            
            // 添加服务员详细信息
            if (record.getServiceStaffId() != null) {
                com.ruoyi.common.core.domain.entity.SysUser serviceStaff = userMap.get(record.getServiceStaffId());
                if (serviceStaff != null) {
                    enhancedRecord.put("serviceStaffName", serviceStaff.getUserName());
                }
            }
            
            // 添加DJ详细信息
            if (record.getDjId() != null) {
                com.ruoyi.common.core.domain.entity.SysUser dj = userMap.get(record.getDjId());
                if (dj != null) {
                    enhancedRecord.put("djName", dj.getUserName());
                }
            }
            
            result.add(enhancedRecord);
        }
        
        log.info("最终返回记录数: {}", result.size());
        return success(result);
    }

    /**
     * 查询同一天角色为业务员的用户在两个及以上房间的工作分布情况
     */
    @GetMapping("/searchNotOneRoomRecord")
    public AjaxResult searchNotOneRoomRecord(
            @RequestParam(value = "date", required = false) String date,
            @RequestParam(value = "roomId", required = false) String roomId) {
        
        org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(RoomRecordmessageController.class);
        log.info("开始查询二班业务员记录，日期: {}, 房间号: {}", date, roomId);
        
        // 构建查询条件
        RoomRecordmessage queryCondition = new RoomRecordmessage();
        
        // 如果指定了房间号，添加到查询条件
        if (org.apache.commons.lang3.StringUtils.isNotBlank(roomId)) {
            try {
                queryCondition.setRoomId(Long.parseLong(roomId));
            } catch (NumberFormatException e) {
                return error("房间号格式不正确");
            }
        }
        
        // 查询符合条件的记录
        List<RoomRecordmessage> allRecords = roomRecordmessageService.selectRoomRecordmessageList(queryCondition);
        log.info("查询到总记录数: {}", allRecords.size());
        
        // 如果指定了日期，进行日期过滤
        if (org.apache.commons.lang3.StringUtils.isNotBlank(date)) {
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
            allRecords = allRecords.stream()
                .filter(record -> record.getRecordTime() != null)
                .filter(record -> {
                    try {
                        String recordDate = sdf.format(record.getRecordTime());
                        return date.equals(recordDate);
                    } catch (Exception e) {
                        return false;
                    }
                })
                .collect(java.util.stream.Collectors.toList());
            log.info("日期过滤后记录数: {}", allRecords.size());
        }
        
        // 构建用户-日期-房间映射
        java.util.Map<String, java.util.Map<String, java.util.List<RoomRecordmessage>>> userDateRoomMap = new java.util.HashMap<>();
        java.util.Set<Long> allUserIds = new java.util.HashSet<>();
        
        // 第一次遍历：收集所有用户ID和构建用户日期房间映射
        for (RoomRecordmessage record : allRecords) {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(record.getGroupName()) && record.getRecordTime() != null) {
                String[] userIds = record.getGroupName().split(",");
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
                String recordDate = sdf.format(record.getRecordTime());
                for (String userIdStr : userIds) {
                    try {
                        Long userId = Long.parseLong(userIdStr.trim());
                        allUserIds.add(userId); // 收集所有用户ID
                        userDateRoomMap
                            .computeIfAbsent(userIdStr, k -> new java.util.HashMap<>())
                            .computeIfAbsent(recordDate, k -> new java.util.ArrayList<>())
                            .add(record);
                    } catch (Exception e) {
                        // userId 不是数字，跳过
                    }
                }
            }
        }
        log.info("收集到的用户ID数量: {}", allUserIds.size());
        
        // 批量查询所有用户信息
        java.util.Map<Long, com.ruoyi.common.core.domain.entity.SysUser> userMap = new java.util.HashMap<>();
        if (!allUserIds.isEmpty()) {
            // 逐个查询用户信息，确保包含角色信息
            for (Long userId : allUserIds) {
                try {
                    com.ruoyi.common.core.domain.entity.SysUser user = userService.selectUserById(userId);
                    if (user != null) {
                        userMap.put(userId, user);
                    }
                } catch (Exception e) {
                    log.warn("查询用户信息失败，用户ID: {}, 错误: {}", userId, e.getMessage());
                }
            }
        }
        log.info("查询到的用户信息数量: {}", userMap.size());
        
        // 重新设计返回结构：按二班业务员分组，显示每个业务员的工作房间分布
        java.util.List<java.util.Map<String, Object>> result = new java.util.ArrayList<>();
        
        for (java.util.Map.Entry<String, java.util.Map<String, java.util.List<RoomRecordmessage>>> entry : userDateRoomMap.entrySet()) {
            String userIdStr = entry.getKey();
            java.util.Map<String, java.util.List<RoomRecordmessage>> dateMap = entry.getValue();
            
            try {
                Long userId = Long.parseLong(userIdStr);
                com.ruoyi.common.core.domain.entity.SysUser user = userMap.get(userId);
                
                // 检查是否为业务员
                boolean isYewuyuan = false;
                if (user != null && user.getRoles() != null) {
                    for (com.ruoyi.common.core.domain.entity.SysRole role : user.getRoles()) {
                        if ("yewuyuan".equals(role.getRoleKey())) {
                            isYewuyuan = true;
                            break;
                        }
                    }
                }
                
                // 只有业务员才继续处理
                if (isYewuyuan) {
                    log.info("找到业务员用户: {} ({})", user.getUserName(), userId);
                    
                    // 检查该业务员在同一天是否有两个及以上房间记录
                    for (java.util.List<RoomRecordmessage> records : dateMap.values()) {
                        if (records.size() >= 2) {
                            log.info("业务员 {} 在同一天有 {} 个房间记录", user.getUserName(), records.size());
                            
                            // 构建二班业务员的工作分布信息
                            java.util.Map<String, Object> businessUserInfo = new java.util.HashMap<>();
                            
                            // 业务员基本信息
                            businessUserInfo.put("userId", user.getUserId());
                            businessUserInfo.put("userName", user.getUserName());
                            businessUserInfo.put("employeeId", user.getEmployeeId());
                            businessUserInfo.put("level", user.getLevel());
                            businessUserInfo.put("roomCount", records.size());
                            
                            // 构建房间信息列表（只包含房间基本信息，不包含业务员详情）
                            java.util.List<java.util.Map<String, Object>> roomInfoList = new java.util.ArrayList<>();
                            for (RoomRecordmessage record : records) {
                                java.util.Map<String, Object> roomInfo = new java.util.HashMap<>();
                                roomInfo.put("roomId", record.getRoomId());
                                roomInfo.put("roomName", record.getCc()); // 房间名称
                                roomInfo.put("area", record.getArea());
                                roomInfo.put("price", record.getPrice());
                                roomInfo.put("purpose", record.getPurpose());
                                roomInfo.put("startTime", record.getStartTime());
                                roomInfo.put("endTime", record.getEndTime());
                                roomInfo.put("totalAmount", record.getTotalAmount());
                                roomInfo.put("recordTime", record.getRecordTime());
                                roomInfoList.add(roomInfo);
                            }
                            businessUserInfo.put("rooms", roomInfoList);
                            
                            result.add(businessUserInfo);
                            break; // 一个业务员只添加一次，即使有多天记录
                        }
                    }
                }
            } catch (Exception e) {
                // 跳过无效的用户ID
                log.warn("处理用户ID {} 时发生异常: {}", userIdStr, e.getMessage());
            }
        }
        
        log.info("最终返回二班业务员数: {}", result.size());
        return success(result);
    }
}
